package Utility;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Utility {
	public static void logMessage(String message, String filename) {
		try{
			BufferedWriter f = new BufferedWriter(new FileWriter(filename, true));
			f.write(message + "\n");			
			f.close();
		}
		catch(IOException e)
		{
			e.printStackTrace();
		}
	}
	
	public static String getScreennameFromTweetID(int tweet_table_id)
	{
		//to get the screen name, you must obtain the user id from the tweet table,
		//then the screen name from the users table
		int user_id =  0;
		String screen_name = "";
		try {
			
			Class.forName("org.sqlite.JDBC");
			Connection conn = DriverManager.getConnection("jdbc:sqlite:twitter.db");
			
			//Statement stmt = conn.createStatement();
			Statement stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
			ResultSet srs = stmt.executeQuery("SELECT user_id FROM tweets WHERE id = " + tweet_table_id);
			srs.next();
			if (srs.isAfterLast())
			{
				Utility.logMessage("No such tweet table Id: " + tweet_table_id, "Utility_errorlog.txt");
				stmt.close();
				srs.close();
				conn.close();
				return "";
			}
			user_id = srs.getInt("user_id");
			stmt.close();
			srs.close();
			
			stmt = conn.createStatement();
			srs = stmt.executeQuery("SELECT screen_name FROM users WHERE user_id = " + user_id);
			srs.next();
			if (srs.isAfterLast())
			{
				Utility.logMessage("No such user ID: " + user_id, "Utility_errorlog.txt");
				stmt.close();
				srs.close();
				conn.close();
				return "";
			}
			screen_name = srs.getString("screen_name");
			stmt.close();
			srs.close();
			
			conn.close();
		}
		catch(SQLException e){
			e.printStackTrace();
			Utility.logMessage("Error getting screen_name for tweet_table_id: " + tweet_table_id,
							   "Utility_errorlog.txt");
		}
		catch(Exception e){
			e.printStackTrace();
			Utility.logMessage("Error getting screen_name for tweet_table_id: " + tweet_table_id,
			   				   "Utility_errorlog.txt");
		}
		
		return screen_name;
	}
}
